<template>
  <div class="Editors">
    <textarea :id="id" :value="contents"></textarea>
  </div>
</template>

<script>
import { upload as UploadImage } from '@/api/oss';
import { blobToFile } from '@/utils/common';

export default {
  name: 'Editors',
  props: {
    contents: String
  },
  data() {
    return {
      accept: 'image/jpeg, image/png, image/*',
      videoaccept: 'video/mp4',
      maxSize: 20 * 1024 * 1024,
      videoSize: 100,
      inits: false,
      editor: '',
      id: 'tiny' + new Date().getTime()
    };
  },
  components: {
  },
  created() {},
  mounted() {
    this.init();
  },
  beforeDestroy() {
    this.editor && this.editor.destroy();
  },

  methods: {
    /* eslint-disable */
    init() {
      console.log('init');
      this.$nextTick(() => {
      const that = this;
      tinymce.init({
        selector: `#${that.id}`,
        branding: false,
        // skin:'oxide-dark',
        language: 'zh_CN',
        plugins: 'print preview searchreplace autolink directionality visualblocks visualchars fullscreen image link media template code codesample table charmap hr pagebreak nonbreaking anchor insertdatetime importword advlist lists powerpaste wordcount imagetools axupimgs textpattern help emoticons autosave lineheight formatpainter',
        toolbar: 'code undo redo restoredraft | cut copy | forecolor backcolor bold italic underline strikethrough link anchor | alignleft aligncenter alignright alignjustify outdent indent | styleselect formatselect fontselect powerpaste fontsizeselect lineheight | bullist numlist | blockquote subscript superscript removeformat | table image axupimgs media importword charmap emoticons hr pagebreak insertdatetime print preview formatpainter | fullscreen',
        height: 600, // 编辑器高度
        min_height: 600,
        powerpaste_word_import: 'propmt',// 参数可以是propmt, merge, clear，效果自行切换对比
        powerpaste_html_import: 'propmt',// propmt, merge, clear
        powerpaste_allow_local_images: true,
        paste_data_images: true,
        content_style: 'img {max-width:100%;}p{margin: 0;line-height: 2}',
        /* content_css: [ //可设置编辑区内容展示的css，谨慎使用
            '/static/reset.css',
            '/static/ax.css',
            '/static/css.css',
        ], */
        fontsize_formats: '12px 14px 16px 18px 24px 36px 48px 56px 72px',
        font_formats: '微软雅黑=Microsoft YaHei,Helvetica Neue,PingFang SC,sans-serif;苹果苹方=PingFang SC,Microsoft YaHei,sans-serif;宋体=simsun,serif;仿宋体=FangSong,serif;黑体=SimHei,sans-serif;Arial=arial,helvetica,sans-serif;Arial Black=arial black,avant garde;Book Antiqua=book antiqua,palatino;Comic Sans MS=comic sans ms,sans-serif;Courier New=courier new,courier;Georgia=georgia,palatino;Helvetica=helvetica;Impact=impact,chicago;Symbol=symbol;Tahoma=tahoma,arial,helvetica,sans-serif;Terminal=terminal,monaco;Times New Roman=times new roman,times;Verdana=verdana,geneva;Webdings=webdings;Wingdings=wingdings,zapf dingbats;',
        link_list: [
            { title: '预置链接1', value: 'https://www.baidu.com' }
        ],
        image_list: [
            { title: '预置图片2', value: 'https://www.baidu.com/img/bd_logo1.png' }
        ],
        image_class_list: [
        { title: 'None', value: '' },
        { title: 'Some class', value: 'class-name' }
        ],
        style_formats: [
          {
            title: '首行缩进',
            block: 'p',
            styles: { 'text-indent': '2em' }
          },
          {
            title: 'Headings',
            items: [
              { title: 'Heading 1', format: 'h1' },
              { title: 'Heading 2', format: 'h2' },
              { title: 'Heading 3', format: 'h3' },
              { title: 'Heading 4', format: 'h4' },
              { title: 'Heading 5', format: 'h5' },
              { title: 'Heading 6', format: 'h6' }
            ]
          },
          {
            title: 'Inline',
            items: [
              { title: 'Bold', format: 'bold' },
              { title: 'Italic', format: 'italic' },
              { title: 'Underline', format: 'underline' },
              { title: 'Strikethrough', format: 'strikethrough' },
              { title: 'Superscript', format: 'superscript' },
              { title: 'Subscript', format: 'subscript' },
              { title: 'Code', format: 'code' }
            ]
          },
          {
            title: 'Blocks',
            items: [
              { title: 'Paragraph', format: 'p' },
              { title: 'Blockquote', format: 'blockquote' },
              { title: 'Div', format: 'div' },
              { title: 'Pre', format: 'pre' }
            ]
          },
          {
            title: 'Align',
            items: [
              { title: 'Left', format: 'alignleft' },
              { title: 'Center', format: 'aligncenter' },
              { title: 'Right', format: 'alignright' },
              { title: 'Justify', format: 'alignjustify' }
            ]
          }
        ],
        // importcss_append: true,
        // 自定义文件选择器的回调内容
        file_picker_callback: function(callback, value, meta) {
            // if (meta.filetype === 'file') {
            //   callback('https://www.baidu.com/img/bd_logo1.png', { text: 'My text' });
            // }
            // if (meta.filetype === 'image') {
            //   callback('https://www.baidu.com/img/bd_logo1.png', { alt: 'My alt text' });
            // }
            // if (meta.filetype === 'media') {
            //   callback('movie.mp4', { source2: 'alt.ogg', poster: 'https://www.baidu.com/img/bd_logo1.png' });
            // }

            if (meta.filetype == 'media') {
              // 创建一个隐藏的type=file的文件选择input
              const input = document.createElement('input');
              input.setAttribute('type', 'file');
              input.setAttribute('accept', 'video/mp4');
              input.onchange = function() {
                const file = this.files[0]; // 只选取第一个文件。如果要选取全部，后面注意做修改
                if (file.size / 1024 / 1024 > that.videoSize) {
                  alert('视频不能超过' + that.videoSize + '兆');
                  return;
                }

                if (that.videoaccept.indexOf(file.type) >= 0) {
                  const formdata = new FormData()
                  formdata.append('file', file)
                  UploadImage(formdata)
                    .then(res => {
                      console.log(res);
                      callback(res.data.imgUrl, { text: file.name });
                    })
                    .catch(err => {
                      console.log('err', err);
                    });
                } else {
                  alert('请上传mp4格式的视频');
                }
              };
              // 触发点击
              input.click();
            }
        },
        // 为内容模板插件提供预置模板
        templates: [
            { title: '模板1', description: '介绍文字1', content: '模板内容' },
            { title: '模板2', description: '介绍文字2', content: '<div class="mceTmpl"><span class="cdate">CDATE</span>，<span class="mdate">MDATE</span>，我的内容</div>' }
        ],
        // content_security_policy: "script-src *;",
        extended_valid_elements: 'script[src]',
        //
        template_cdate_format: '[CDATE: %m/%d/%Y : %H:%M:%S]',
        template_mdate_format: '[MDATE: %m/%d/%Y : %H:%M:%S]',
        autosave_ask_before_unload: false,
        toolbar_mode: 'wrap',
        // images_upload_base_path: '',
        images_upload_handler: function(blobInfo, successFun, failure) {
          console.log(blobInfo);
          let file = blobInfo.blob()
          if(Object.prototype.toString.call(file) == '[object Blob]') {
            file = blobToFile(file, new Date().getTime() + '.' + file.type.substring(file.type.indexOf('/') + 1, file.type.length), file.type)
          }

          if (file.size > that.maxSize) {
            failure('图片不要超过20兆');
            return;
          }

          if (that.accept.indexOf(file.type) >= 0) {
            const formdata = new FormData()
            formdata.append('file', file)
            UploadImage(formdata)
              .then(res => {
                console.log('upload success', res);
                successFun(res.data.imgUrl);
              })
              .catch(err => {
                console.log('err', err);
              });
          } else {
            failure('图片格式错误');
          }
        },
        init_instance_callback: function(editor) {
          this.editor = editor;
          // EDITOR = editor
          // console.log("Editor: " + editor.id + " is now initialized.");
          editor.on('input change undo redo', () => {
            var content = editor.getContent();
            that.$emit('getContent', { content });
          });
        }
        // images_upload_handler: function(blobInfo, succFun, failFun) {
        //   console.log(blobInfo);
        //     succFun('/demo/images/img.jpg');
        // }
        // icons:'ax-color',

      });
    });
    }
  }
};
</script>

<style scoped>
  .Editors {
    width: 100%;
  }
</style>
